<?php

class Identity
{
    private static $_instance = null;

    private $_id = null;
    private $_username = null;
    private $_role = null;

    public static function getInstance()
    {
        if (self::$_instance == null) {

            $CI          =& get_instance();
            $sesIdentity = $CI->session->getObject('Identity');

            if ($sesIdentity) {

                self::$_instance = $sesIdentity;
            } else {

                self::$_instance = new Identity();
                $CI->session->storeObject('Identity', self::$_instance);
            }
        }

        return self::$_instance;
    }

    public function getCookieValue()
    {
        return array(
            'uid'   => $this->_id,
            'uname' => $this->_username,
            'urole' => $this->_role
        );
    }

    /**
     * @return null
     */
    public function getId()
    {
        return $this->_id;
    }

    public function getUsername()
    {
        return $this->_username;
    }

    public function authenticate($id, $username, $role, $remember)
    {
        $this->_id       = $id;
        $this->_username = $username;
        $this->_role     = $role;

        //TODO: Set cookie used for remember authenticate

        $this->_saveIdentity();
    }

    public function getRole()
    {
        return $this->_role;
    }

    private function _saveIdentity()
    {
        $CI =& get_instance();
        $CI->session->storeObject('Identity', $this);
    }

    public function isLoggedIn()
    {
        return ($this->_id != null && $this->_username != null) ? TRUE : FALSE;
    }

    public function signOut()
    {
        if($this->isLoggedIn()) {

            $this->_id       = null;
            $this->_username = null;
            $this->_role     = null;

            $CI =& get_instance();
            $CI->session->storeObject('Identity', '');
        }
    }
}